package com.yantu.controller.wx;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.*;
import com.yantu.mapper.*;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.PageView;
import com.yantu.view.wx.addAnswerPaper.AnswerList;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-13
 */
@RestController
@RequestMapping("/wx")
@ApiModel("试卷信息类")
public class WxExamPaperController extends WxUserFatherController {
    @Autowired
    ExamPaperQuestionCustomerAnswerMapper examPaperQuestionCustomerAnswerMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ExamPaperAnswerMapper examPaperAnswerMapper;

    @Autowired
    SubjectMapper subjectMapper;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    ExamPaperMapper examPaperMapper;

    @Autowired
    TextContentMapper textContentMapper;

    @Autowired
    RedisUtils redisUtils;

    //试卷列表
    @GetMapping("/paperList")
    @ApiOperation("试卷列表")
    public Result getPaperList(PageView pageView) {
        if(redisUtils.haskeysf("wxPaperList"+pageView)){
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("wxPaperList"+pageView);
            return Result.succ(200, "成功", pageInfo);
        }else {
            PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
            QueryWrapper<ExamPaper> queryWrapper = new QueryWrapper<>();
            if (pageView.getPaperType() != null) {
                queryWrapper.eq("paper_type", pageView.getPaperType());
            }
            List<ExamPaper> list = examPaperMapper.selectList(queryWrapper);
            if (list != null) {
                List<Object> list1 = new ArrayList<>();
                for (ExamPaper example : list) {
                    Map<String, Object> map = new HashMap();
                    map.put("id", example.getId());
                    map.put("name", example.getName());
                    map.put("questionCount", example.getQuestionCount());
                    map.put("score", example.getScore());
                    map.put("createTime", example.getCreateTime());
                    map.put("create_user", example.getCreateUser());
                    map.put("subjectId", example.getSubjectId());
                    Subject subject = subjectMapper.selectById(example.getSubjectId());
                    map.put("subjectName", subject.getName());
                    map.put("paperType", example.getPaperType());
                    map.put("frameTextContentId", example.getFrameTextContentId());
                    map.put("startTime", example.getLimitStartTime());
                    map.put("endTime", example.getLimitEndTime());
                    if (example.getPaperType() == 1) {
                        map.put("paperTypeStr", "固定试卷");
                    }
                    if (example.getPaperType() == 4) {
                        map.put("paperTypeStr", "时段试卷");
                    }
                    if (example.getPaperType() == 6) {
                        map.put("paperTypeStr", "任务试卷");
                    }
                    map.put("scoreStr", example.getScore());
                    map.put("suggestTimeStr", example.getSuggestTime() + "分钟");
                    list1.add(map);
                }
                PageInfo pageInfo = new PageInfo(list1);
                redisUtils.saveValueTime("wxPaperList"+pageView,pageInfo,1);
                return Result.succ(200, "成功", pageInfo);
            } else {
                return Result.succ("没有数据", null);
            }
        }
    }

    //    //试卷查询
    @GetMapping("/paper/{id}")
    @ApiOperation("试卷查询")
    public Result paperSelect(@PathVariable("id") Integer id) {
        if(redisUtils.haskeysf("wxPaper"+id)){
            List<Object> list = (List<Object>) redisUtils.getValue("wxPaper"+id);
            return Result.succ(200, "成功", list);
        }else {
            ExamPaper examPaper = examPaperMapper.selectById(id);
            List<Object> list = new ArrayList();
            //每一张试卷
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", examPaper.getId());
            map.put("level", examPaper.getGradeLevel());
            map.put("subjectId", examPaper.getSubjectId());
            map.put("paperType", examPaper.getPaperType());
            map.put("name", examPaper.getName());
            map.put("suggestTime", examPaper.getSuggestTime());
            map.put("limitDateTime", null);
            List<Object> list1 = new ArrayList();
            HashMap<String, Object> map1 = new HashMap<>();
            //将Exam_paper表和text_content对应起来
            TextContent textContent = textContentMapper.selectById(examPaper.getFrameTextContentId());
            JSONArray contentArray = JSONArray.fromObject(textContent.getContent());
            JSONObject content = contentArray.getJSONObject(0);
            map1.put("name", content.getString("name"));
            List<Object> list2 = new ArrayList();
            JSONArray questionItemArray = JSONArray.fromObject(content.getString("questionItems"));

            for (int i = 0; i < questionItemArray.size(); i++) {
                System.out.println("第一个长度为：");
                System.out.println(questionItemArray.size());
                System.out.println("目前为：");
                System.out.println(i);
                JSONObject qusetion = questionItemArray.getJSONObject(i);
                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("id", qusetion.getString("id"));
                map2.put("itemOrder", qusetion.getString("itemOrder"));
                Question questionItem = questionMapper.selectById(qusetion.getString("id"));
                map2.put("questionType", questionItem.getQuestionType());
                map2.put("subjectId", questionItem.getSubjectId());
                map2.put("score", questionItem.getScore());
                map2.put("gradeLevel", questionItem.getGradeLevel());
                map2.put("difficult", questionItem.getDifficult());
                map2.put("correct", questionItem.getCorrect());
                String[] answer = questionItem.getCorrect().split(",");
                List<String> correctList = new ArrayList<>();
                for (int j = 0; j < answer.length; j++) {
                    correctList.add(answer[j]);
                }
                map2.put("correctArray", correctList);
                if (questionItem.getInfoTextContentId() != null) {
                    TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
                    JSONObject content1 = JSONObject.fromObject(textContent1.getContent());

                    map2.put("title", content1.getString("titleContent"));
                    map2.put("analyze", content1.getString("analyze"));
                    JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                    List<Object> answList = new ArrayList<>();
                    if (contentObject1.size() == 0) {
                        map2.put("items", null);
                    } else {
                        for (int m = 0; m < contentObject1.size(); m++) {
                            System.out.println("长度为：");
                            System.out.println(contentObject1.size());
                            JSONObject xuanxiang = contentObject1.getJSONObject(m);
                            Map<String, String> map4 = new HashMap();
                            map4.put("prefix", xuanxiang.getString("prefix"));
                            map4.put("content", xuanxiang.getString("content"));
                            map4.put("score", xuanxiang.getString("score"));
                            answList.add(map4);
                        }
                    }
                    map2.put("items", answList);
                }
                list2.add(map2);
            }
            map1.put("questionItems", list2);
            list1.add(map1);
            map.put("titleItems", list1);
            map.put("score", examPaper.getScore());
            list.add(map);
            redisUtils.saveValue("wxPaper"+id,list);
            return Result.succ(200, "查询成功", list);
        }
    }

    //答卷列表
    @GetMapping("/answerList")
    @ApiOperation("答卷列表")
    public Result answerList(@ModelAttribute PageView pageView) {

        if(redisUtils.haskeysf("wxAnswerList"+pageView)){
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("wxAnswerList"+pageView);
            return Result.succ(200, "成功", pageInfo);
        }else {
            QueryWrapper<ExamPaperAnswer> queryWrapper = new QueryWrapper<>();
            if (pageView.getPaperType() != null) {
                queryWrapper.eq("paper_type", pageView.getPaperType());
            }
            List<ExamPaperAnswer> list = examPaperAnswerMapper.selectList(queryWrapper);
            System.out.println("搜出来的所有list在这里");
            System.out.println(list.size());
            if (list != null) {
                List<Object> list1 = new ArrayList<>();
                int i = 0;
                for (ExamPaperAnswer example : list) {
                    System.out.println("小列表");
                    System.out.println("当前为：");
                    System.out.println(i);
                    i++;
                    System.out.println(example);
                    Map<String, Object> map = new HashMap();
                    map.put("id", example.getId());
                    map.put("createTime", example.getCreateTime());
                    map.put("subjectId", example.getSubjectId());
                    map.put("userScore", example.getUserScore());
                    map.put("questionCount", example.getQuestionCount());
                    map.put("questionCorrect", example.getQuestionCorrect());
                    map.put("paperScore", example.getPaperScore());
                    map.put("doTime", example.getDoTime());
                    map.put("paperType", example.getPaperType());
                    map.put("systemScore", example.getSystemScore());
                    map.put("status", example.getStatus());
                    Subject subject = subjectMapper.selectById(example.getSubjectId());
                    map.put("subjectName", subject.getName());
                    map.put("paperName", example.getPaperName());
                    User user = userMapper.selectById(example.getCreateUser());
                    map.put("userName", user.getUserName());
                    if (example.getPaperType() == 1) {
                        map.put("paperTypeStr", "固定试卷");
                    }
                    if (example.getPaperType() == 4) {
                        map.put("paperTypeStr", "时段试卷");
                    }
                    if (example.getPaperType() == 6) {
                        map.put("paperTypeStr", "任务试卷");
                    }
                    list1.add(map);
                }
                PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
                PageInfo pageInfo = new PageInfo(list1);
                redisUtils.saveValue("wxAnswerList"+pageView,pageInfo);
                return Result.succ(200, "成功", pageInfo);
            } else {
                return Result.succ("没有数据", null);
            }
        }
    }

    //答卷详情
    @ApiOperation("答卷详情")
    @GetMapping("/answerPaperDetails/{id}")//id为答题卡id
    public Result answerPaperDetails(@PathVariable Integer id) {
        if(redisUtils.haskeysf("wxAnswerPaperDetails"+id)){
            Map<String, Object> mapAll = (Map<String, Object>) redisUtils.getValue("wxAnswerPaperDetails"+id);
            return Result.succ(200, "成功",mapAll);
        }else {
            //获取答题卡id
            ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectById(id);
            //获取试卷信息
            ExamPaper examPaper = examPaperMapper.selectById(examPaperAnswer.getExamPaperId());
            Map<String, Object> mapAll = new HashMap<>();//总的map
            //每一张试卷答题卡
            HashMap<String, Object> map = new HashMap<>();//paper的map
            HashMap<String, Object> mapS = new HashMap<>();//answer的map
            mapS.put("id", examPaperAnswer.getId());
            mapS.put("doTime", examPaperAnswer.getDoTime());
            mapS.put("score", examPaperAnswer.getUserScore());
            map.put("id", examPaper.getId());
            map.put("level", examPaper.getGradeLevel());
            map.put("subjectId", examPaper.getSubjectId());
            map.put("paperType", examPaper.getPaperType());
            map.put("name", examPaper.getName());
            map.put("suggestTime", examPaper.getSuggestTime());
            //时间
            List<Object> listTime = new ArrayList<>();
            if (examPaper.getLimitStartTime() != null && examPaper.getLimitEndTime() != null) {
                listTime.add(examPaper.getLimitStartTime());
                listTime.add(examPaper.getLimitEndTime());
                map.put("limitDateTime", listTime);
            } else {
                map.put("limitDateTime", null);
            }
            List<Object> list1 = new ArrayList();//titleItems的list
            HashMap<String, Object> map1 = new HashMap<>();//titleItems里面的map
            //去textcontent里面找titleItems
            TextContent textContent = textContentMapper.selectById(examPaper.getFrameTextContentId());
            JSONArray contentArray = JSONArray.fromObject(textContent.getContent());
            JSONObject content = contentArray.getJSONObject(0);
            map1.put("name", content.getString("name"));
            List<Object> list2 = new ArrayList();//questionItems里面的题目列表
            JSONArray questionItemArray = JSONArray.fromObject(content.getString("questionItems"));
            Map<String, Object> mapS1 = new HashMap<>();
            List<Object> listS1 = new ArrayList<>();
            for (int i = 0; i < questionItemArray.size(); i++) {
                JSONObject qusetion = questionItemArray.getJSONObject(i);
                HashMap<String, Object> map2 = new HashMap<>();//用来放每一个题目信息
                Map<String, Object> mapS2 = new HashMap<>();//answerItem里面的每一个
                mapS2.put("itemOrder", qusetion.getString("itemOrder"));
                mapS2.put("questionId", qusetion.getString("id"));
                map2.put("id", qusetion.getString("id"));
                map2.put("itemOrder", qusetion.getString("itemOrder"));
                QueryWrapper<ExamPaperQuestionCustomerAnswer> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("question_id", qusetion.getString("id"));
                queryWrapper.eq("exam_paper_answer_id", examPaperAnswer.getId());
                queryWrapper.eq("item_order", qusetion.getString("itemOrder"));
                ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = examPaperQuestionCustomerAnswerMapper.selectOne(queryWrapper);
                mapS2.put("id", examPaperQuestionCustomerAnswer.getId());
                mapS2.put("doRight", examPaperQuestionCustomerAnswer.getDoRight());
                mapS2.put("score", examPaperQuestionCustomerAnswer.getCustomerScore());
                Question questionItem = questionMapper.selectById(qusetion.getString("id"));
                map2.put("questionType", questionItem.getQuestionType());
                if (questionItem.getQuestionType() == 5) {//简答题
                    if (examPaperQuestionCustomerAnswer.getTextContentId() != null) {
                        TextContent myContent = textContentMapper.selectById(examPaperQuestionCustomerAnswer.getTextContentId());
                        mapS2.put("content", myContent.getContent());
                    } else {
                        mapS2.put("content", null);
                    }
                    mapS2.put("contentArray", null);
                } else {//非简答题

                    if (examPaperQuestionCustomerAnswer.getTextContentId() != null) {
                        TextContent myContent = textContentMapper.selectById(examPaperQuestionCustomerAnswer.getTextContentId());
                        mapS2.put("contentArray", myContent.getContent());
                    } else {
                        mapS2.put("contentArray", null);
                    }
                    mapS2.put("content", null);
                }
                listS1.add(mapS2);
                map2.put("subjectId", questionItem.getSubjectId());
                map2.put("score", questionItem.getScore());
                mapS2.put("questionScore", questionItem.getScore());
                map2.put("gradeLevel", questionItem.getGradeLevel());
                map2.put("difficult", questionItem.getDifficult());
                map2.put("correct", questionItem.getCorrect());
                String[] answer = questionItem.getCorrect().split(",");
                List<String> correctList = new ArrayList<>();
                for (int j = 0; j < answer.length; j++) {
                    correctList.add(answer[j]);
                }
                map2.put("correctArray", correctList);
                if (questionItem.getInfoTextContentId() != null) {

                    TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
                    JSONObject content1 = JSONObject.fromObject(textContent1.getContent());

                    map2.put("title", content1.getString("titleContent"));
                    map2.put("analyze", content1.getString("analyze"));
                    JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                    List<Object> answList = new ArrayList<>();
                    if (contentObject1.size() == 0) {
                        map2.put("items", null);
                    } else {
                        for (int m = 0; m < contentObject1.size(); m++) {
                            System.out.println("长度为：");
                            System.out.println(contentObject1.size());
                            JSONObject xuanxiang = contentObject1.getJSONObject(m);
                            Map<String, String> map4 = new HashMap();
                            map4.put("prefix", xuanxiang.getString("prefix"));
                            map4.put("content", xuanxiang.getString("content"));
                            map4.put("score", xuanxiang.getString("score"));
                            answList.add(map4);
                        }
                    }
                    map2.put("items", answList);
                }
                list2.add(map2);
            }
            mapS.put("answerItems", listS1);
            map1.put("questionItems", list2);
            list1.add(map1);
            map.put("titleItems", list1);
            map.put("score", examPaper.getScore());
            mapAll.put("paper", map);
            mapAll.put("answer", mapS);
            redisUtils.saveValue("wxAnswerPaperDetails"+id,mapAll);
            return Result.succ(200, "查询成功", mapAll);
        }
    }

    //试卷提交
    @ApiOperation("试卷提交")
    @PostMapping("/answerSubmit")
    public Result answerPaperDetails(HttpServletRequest request,@RequestBody ArrayList<AnswerList> answerView) {
        String token = request.getHeader("token");
        System.out.println(token);
        System.out.println(answerView);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(token!=null){
            queryWrapper.eq("token",token);
        }
        User user = userMapper.selectOne(queryWrapper);
        int m=0;
        int allScore = 0;
        int correctCount = 0;
        int examPaperAnswerId = 0;
        for (AnswerList answer:answerView) {
            System.out.println("第几个呀");
            System.out.println(answer);
            if(m==0){
                //如果是第一个则向exam_paper_answer表中插入一条数据
                ExamPaper examPaper = examPaperMapper.selectById(answer.getPaperId());
                ExamPaperAnswer examPaperAnswer = new ExamPaperAnswer();
                examPaperAnswer.setExamPaperId(examPaper.getId());
                examPaperAnswer.setPaperName(examPaper.getName());
                examPaperAnswer.setPaperType(examPaper.getPaperType());
                examPaperAnswer.setCreateTime(new Date());
                examPaperAnswer.setPaperName(examPaper.getName());
                examPaperAnswer.setDoTime(answer.getDoTime());
                examPaperAnswer.setStatus(1);
                examPaperAnswer.setSubjectId(examPaper.getSubjectId());
                examPaperAnswer.setQuestionCount(examPaper.getQuestionCount());
                examPaperAnswer.setPaperScore(examPaper.getScore());
                examPaperAnswer.setCreateUser(user.getId());
//
                int result =  examPaperAnswerMapper.insert(examPaperAnswer);
                examPaperAnswerId =  examPaperAnswer.getId();
            }
            //非第一个只需要把数据插入到exam_paper-question_customer中去
            //根据问题id找到正确答案再对比，判断分数
            ExamPaperQuestionCustomerAnswer ePQCA = new ExamPaperQuestionCustomerAnswer();
            ePQCA.setExamPaperAnswerId(examPaperAnswerId);
            ePQCA.setQuestionId(Integer.parseInt(answer.getQId()));
            ePQCA.setExamPaperId(Integer.parseInt(answer.getPaperId()));
            ePQCA.setCreateTime(new Date());
            ePQCA.setCreateUser(user.getId());
            Question question = questionMapper.selectById(answer.getQId());
            if(Integer.parseInt(answer.getQType())==4||Integer.parseInt(answer.getQType())==5){//简答题,填空题
                ePQCA.setAnswer(null);
                TextContent textContent = new TextContent();
                textContent.setContent(answer.getMyAnswer());
                textContent.setCreateTime(new Date());
                int result2 = textContentMapper.insert(textContent);
                ePQCA.setTextContentId(textContent.getId());
                ePQCA.setDoRight(0);
                ePQCA.setCustomerScore(0);
            }else {
                System.out.println("分数为");
                System.out.println(question.getCorrect());
                System.out.println(answer.getMyAnswer());
                System.out.println(question.getCorrect().equals(answer.getMyAnswer()));
                System.out.println(question.getCorrect()==answer.getMyAnswer());
                if(question.getCorrect().equals(answer.getMyAnswer())){//答对
                    System.out.println("分数为");
                    System.out.println(question.getCorrect());
                    System.out.println(answer.getMyAnswer());
                    allScore = allScore+question.getScore();
                    System.out.println(question.getScore());
                    System.out.println(allScore);
                    correctCount+=1;
                    ePQCA.setDoRight(1);
                    ePQCA.setCustomerScore(question.getScore());//用户小题得分
                }else {//答错
                    ePQCA.setDoRight(0);
                    ePQCA.setCustomerScore(0);
                }
                ePQCA.setAnswer(answer.getMyAnswer());
                ePQCA.setTextContentId(null);
            }
            ePQCA.setItemOrder(Integer.parseInt(answer.getQOrder()));
            ePQCA.setQuestionType(Integer.parseInt(answer.getQType()));
            ePQCA.setQuestionScore(question.getScore());//小题原始分数
            ePQCA.setQuestionTextContentId(question.getInfoTextContentId());

            int resultE  = examPaperQuestionCustomerAnswerMapper.insert(ePQCA);
            if(resultE>0){
                m++;
            }else {
                return Result.fail("出现错误");
            }
        }
        UpdateWrapper updateWrapper22 = new UpdateWrapper();
        updateWrapper22.eq("id",examPaperAnswerId);
        updateWrapper22.set("system_score",allScore);
        updateWrapper22.set("user_score",allScore);
        updateWrapper22.set("question_correct",correctCount);
        int result5 = examPaperAnswerMapper.update(null,updateWrapper22);
        if(result5>0){
            String msg = "学生"+user.getUserName()+"提交试卷成功";
            super.wxAddLog(user,msg);
            redisUtils.delAll();
            return Result.succ("提交成功",allScore);
        }else {
            String msg = "学生"+user.getUserName()+"提交试卷失败";
            super.wxAddLog(user,msg);
            return Result.fail("提交失败") ;
        }
    }
}

